<?php

class Admin_TreeController extends Zend_Controller_Action{
	private $mapper;
    private $mapperHtaccess;
    public function init(){
        parent::init();
    	$this->mapper =  new Admin_Model_TreeNodeMapper();
        $this->mapperHtaccess = new Admin_Model_HtaccessMapper();
    }

    public function childrenAction(){
    	$nodes = null;
    	$pId = (int)$this->getRequest()->getParam('pId',0);
    	if ($pId>0)
    	{
    		$nodes = $this->mapper->fetchChildrens($pId,true);
    	}
    	$this->_helper->json ( $nodes );
    }
    
    public function loadEditorAction(){
    	$req = $this->getRequest();
    	$id = ( int ) $req->getParam ( 'id', 0 );
		$m2 = new Admin_Model_NodeConfigMapper ( );
		
		$node = $this->mapper->find($id);
		$nodeConfig = $m2->find($node->getCfgId());
		
		//list ( $node, $nodeConfig ) = $m->fetchController ( $id );
		
		$req->setParam ( 'node', $node );
		$req->setParam ( 'nodeConfig', $nodeConfig );
		$req->setControllerName ($nodeConfig->getController());
		$req->setModuleName($nodeConfig->getModule());
		$req->setActionName('load-editor');
		$req->setDispatched ( false );
    }
    
    public function refreshUrlAction(){
        $this->_helper->json (
                $this->mapperHtaccess->RefreshUrl(
                        $this->mapper->fetchURLs()
                )
        );
    }
	
	public function refreshNodesAction(){
		$nodes = $this->mapper->fetchAll();
		foreach($nodes as $n){
			if (method_exists($n,'render'))
			{
				$n	->setHTML	($n->render())
	    			->setXML	($n->serialize());
			}
			else
			{
				$n->pack();
			}
			$this->mapper->save($n, Admin_Model_TreeNode::getFields());
			$result = array ('success' => true, 'msg' => 'Узлы обновлены успешно' );
		}
		$this->_helper->json ( $result );
	}
	
	public function refreshSubNodesAction(){
		$nId = $this->getRequest()->getParam('nId',0);
		if ($nId==0) $result = array ('success' => true, 'msg' => 'Не задан узел' );
		$node = $this->mapper->find($nId);
		$nodes = $this->mapper->fetchSubTree($node);
		$nodes[]=$node;
		foreach($nodes as $n){
			if (method_exists($n,'render'))
			{
				$n	->setHTML	($n->render())
	    			->setXML	($n->serialize());
			}
			else
			{
				$n->pack();
			}
			$this->mapper->save($n, Admin_Model_TreeNode::getFields());
			$result = array ('success' => true, 'msg' => 'Узлы обновлены успешно' );
		}
		$this->_helper->json ( $result );
	}
	
	/*public function copySubTreeAction(){
		$id = ( int ) $this->getRequest()->getParam ( 'id', 0 );
		$destId = ( int ) $this->getRequest()->getParam ( 'dId', 0 );
		if (($id==0) || ($destId==0))
			throw new Zend_Exception("Не задан идентификаторы копируемого узла и узла назначения");
		$this->mapper->copyNode($id,$destId,true);
		$result = array ('success' => true, 'msg' => 'Узлы скопированы' );
		$this->_helper->json ( $result );
	}*/
	
	public function copyNodeAction(){
		$id = ( int ) $this->getRequest()->getParam ( 'id', 0 );
		$destId = ( int ) $this->getRequest()->getParam ( 'dId', 0 );
		if (($id==0) || ($destId==0))
			throw new Zend_Exception("Не задан идентификаторы копируемого узла и узла назначения");
		$copySubTree = $this->getRequest()->getParam ( 'withtree', 0 ) == 1;
		$this->mapper->copyNode($id,$destId,$copySubTree);
		$result = array ('success' => true, 'msg' => 'Узел скопирован' );
		$this->_helper->json ( $result );
	}
	
	public function moveNodeAction(){
		$id = ( int ) $this->getRequest()->getParam ( 'id', 0 );
		$destId = ( int ) $this->getRequest()->getParam ( 'dId', 0 );
		if (($id==0) || ($destId==0))
			throw new Zend_Exception("Не задан идентификаторы перемещаемого узла и узла назначения");
		$movetype = (int)$this->getRequest()->getParam ( 'movetype', 0 );
		try{
			$this->mapper->moveNode($id,$destId,$movetype);
			$result = array ('success' => true, 'msg' => 'Узел перемещён' );
		}
		catch(Exception $e)
		{
			$result = array ('success' => true, 'msg' => 'Ошибка' );
			var_dump($e);
		}
		$this->_helper->json ( $result );
	}
	
	public function clearCacheAction(){
		$this->mapper->clearCache();
		$result = array ('success' => true, 'msg' => 'Кеш очищен' );
		$this->_helper->json ( $result );
	}
	
	public function checkTreeAction(){
		$t = $this->mapper->getDbTable();
		$this->view->list1 = $t->fetchAll($t->select()->from($t,array('Id','Name'))->where("LeftId >= RightId"));
		$this->view->row2 = $t->fetchRow($t->select()->from($t,
							array(	'NodesCount'=>new Zend_Db_Expr('COUNT(Id)'),
									'MinLeftId'=>new Zend_Db_Expr('MIN(LeftId)'),
									'MaxRightId'=>new Zend_Db_Expr('MAX(RightId)')
                            )
                    ));
        $this->view->list3 = $t->fetchAll($t->select()->from($t,array('Id','Name'))->where('MOD(RightId - LeftId,2)=0'));
        $this->view->list4 = $t->fetchAll($t->select()->from($t,array('Id','Name'))->where('MOD(LeftId - Level + 2,2)=1'));
        //SELECT t1.id, COUNT(t1.id) AS rep, MAX(t3.right_key) AS max_right FROM my_tree AS t1, my_tree AS t2, my_tree AS t3 WHERE t1.left_key <> t2.left_key AND t1.left_key <> t2.right_key AND t1.right_key <> t2.left_key AND t1.right_key <> t2.right_key GROUP BY t1.id HAVING max_right <> SQRT(4 * rep + 1) + 1        
        $this->_helper->layout()->disableLayout(); 
	}
    public function createNodesFromXlsAction(){
        require_once 'excel_reader2.php';
        $reader = new Spreadsheet_Excel_Reader('add_node.xls');
        $colNames = array('ParentId','Name','LayoutId','URL','Title','MetaKeywords','MetaDescription','CfgId','InMenu','MenuTitle','ChangeFreq','Priority','Tag');
        //check columns
        for($i=0; $i<count($colNames); $i++){
            if ($reader->value(1, $i+1)!= $colNames[$i]) throw new Zend_Exception('First col and row must be '.$colNames[$i]);
        }
        //echo 'Columns ok';
        echo $reader->rowcount();
        $params = array();
        for($i=2; $i<=$reader->rowcount(); $i++){
            $params[] = array(
                            'pId'               =>$reader->value($i, 1)
                            ,'Name'             =>$reader->value($i, 2)
                            ,'LayoutId'         =>$reader->value($i, 3)
                            ,'URL'              =>$reader->value($i, 4)
                            ,'Title'            =>$reader->value($i, 5)
                            ,'MetaKeywords'     =>$reader->value($i, 6)
                            ,'MetaDescription'  =>$reader->value($i, 7)
                            ,'CfgId'            =>$reader->value($i, 8)
                            ,'InMenu'           =>(int)$reader->value($i, 9)
                            ,'MenuTitle'        =>(int)$reader->value($i, 10)
                            ,'ChangeFreq'       =>$reader->value($i, 11)
                            ,'Priority'         =>0 //$reader->value($i, 12)
                            ,'Tag'              =>$reader->value($i, 13)
                        );
        }
        $this->_helper->actionStack('post','tree-node','admin',array('list'=>$params));
    }
}


